const { STATUS_CODE } = require('../../../constants');
/**
 *
 * @param {*} ctx
 * @param {*} next
 * 效验用户名、密码长度，密码长度必须在8～30个字符之间
 */
const validateUserInfo = async (ctx, next) => {
  const { body } = ctx.request;
  const { name, password } = body;
  const nameType = typeof name;
  const pwdType = typeof password;
  let error;
  if (nameType === 'string' && pwdType === 'string') {
    const pwdLength = body.password.length;
    const nameLength = body.name.length;

    if (!(8 <= pwdLength && pwdLength <= 30)) {
      // password
      error = {
        code: STATUS_CODE.FIELD_LENGTH_ERROR,
        field: 'password',
        message: 'bad request，password length must be 8 <= password =< 30',
      };
      error = JSON.stringify(error);
    } else if (!(2 <= nameLength && nameLength <= 20)) {
      // name
      error = {
        code: STATUS_CODE.FIELD_LENGTH_ERROR,
        field: 'name',
        message: 'bad request，name length must be 2 <= name =< 20',
      };
      error = JSON.stringify(error);
    }
  } else {
    error = {
      code: STATUS_CODE.PARAMS_TYPE_ERROR,
      field: nameType === 'string' ? 'password' : 'name',
    };
    error = JSON.stringify(error);
  }
  if (error) {
    ctx.app.emit('error', new Error(error), ctx);
    return;
  }
  await next();
};

module.exports = validateUserInfo;
